<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="dialogVisible"
      :title="title"
      width="850px"
      @close="resetForm('ruleForm')"
    >
      <button-group
        ref="buttonGroup"
        @submitForm="submitForm('ruleForm')"
        @cancel="dialogVisible = false"
      />
      <div class="formTopFont">设备登记单</div>
      <el-row>
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备名称" prop="equipName">
                <el-input
                  v-model.trim="ruleForm.equipName"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="设备编号" prop="equipCode">
                <div style="display: flex; align-items: center">
                  <el-input
                    v-model.trim="ruleForm.equipCode"
                    maxlength="20"
                    show-word-limit
                  />
                  <el-button
                    @click="showQRCode"
                    icon="el-icon-full-screen"
                    style="margin-left: 10px"
                  >
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号" prop="model">
                <el-input
                  v-model="ruleForm.model"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备类型" prop="type">
                <el-input
                  v-model.trim="ruleForm.type"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="使用状况" prop="usageCondition">
                <el-input
                  v-model.trim="ruleForm.usageCondition"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="安装地点" prop="location">
                <el-input
                  v-model.trim="ruleForm.location"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="使用部门" prop="deptId">
                <tree-select
                  ref="treeSelect"
                  style="width: 100%"
                  :props="treeProps"
                  :options="departData"
                  :disabled="false"
                  :accordion="true"
                  :value="ruleForm.deptId"
                  search-key="deptName"
                  @getNode="getValue($event)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="负责人" prop="userId">
                <el-select v-model="ruleForm.userId" style="width: 100%">
                  <el-option
                    v-for="item in userAllList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="购置时间" prop="purchaseDate">
                <el-date-picker
                  v-model="ruleForm.purchaseDate"
                  type="datetime"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期时间"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="ruleForm.remark"
                  type="textarea"
                  rows="3"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <!-- 图档上传 -->
              <el-form-item label="图档上传" prop="fileList">
                <!-- <el-upload action="#" list-type="picture-card" :auto-upload="false"> -->
                <el-upload
                  ref="upload"
                  class="upload-demo"
                  action
                  :http-request="uploadImage"
                  multiple
                  :before-upload="beforeAvatarUpload"
                  :file-list="fileList"
                  list-type="picture-card"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{ file }">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <bottom-font
        v-if="title === '编辑'"
        ref="bottomFont"
        :obj-info="ruleForm"
        :obj-date="ruleForm.createAt"
      />
    </el-dialog>
    <!-- 图片查看 -->
    <resource-preview ref="ResourcePreview" />
    <el-dialog :visible.sync="dialogVisibles">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>

    <!-- 二维码弹窗 -->
    <el-dialog
      :visible.sync="qrCodeDialogVisible"
      title="识别码"
      @close="qrCodeDialogVisible = false"
      width="400px"
    >
      <div style="text-align: center">
        <!-- 图片居中 -->
        <img
          :src="qrCodeUrl"
          alt="二维码"
          style="width: 200px; height: 200px; margin-bottom: 20px"
        />

        <!-- 设备名称和设备ID展示 -->
        <div style="margin-bottom: 20px">
          <p style="margin: 0; font-weight: bold">
            设备: {{ this.ruleForm.equipName + "-" + this.ruleForm.equipCode }}
          </p>
        </div>
        <el-button @click="downloadPDF" type="primary" style="width: 100%"
          >打印</el-button
        >
        <!-- 按钮宽度设置为100% -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import TreeSelect from "@/components/TreeSelect";
import bottomFont from "@/components/BottomFont";
import ResourcePreview from "@/components/ResourcePreview";

export default {
  components: { TreeSelect, bottomFont, ResourcePreview },
  props: {
    userAllList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    const checkName = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/equip/info/verifyNameUnique?equipName=${value}&id=${
          this.ruleForm.id || ""
        }`
      );
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback("设备名称重复！"));
      } else {
        return new Error(callback(res.data.msg));
      }
    };
    return {
      title: "",
      deptList: [],
      ruleForm: {
        equipName: "",
        equipCode: "",
        model: "",
        remark: "",
        location: "",
        deptId: "",
        purchaseDate: "",
        type: "",
        usageCondition: "",
        userId: "",
        fileList: [],
      },
      treeProps: {
        value: "id",
        label: "deptName",
        children: "children",
      },
      rules: {
        equipName: [
          { required: true, message: "设备名称不能为空！", trigger: "blur" },
          { validator: checkName, trigger: "blur" },
        ],
        equipCode: [
          { required: true, message: "设备编号不能为空！", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      departData: [],
      fileList: [],
      dialogImageUrl: "",
      dialogVisibles: false,
      rows: {},
      qrCodeDialogVisible: false,
      qrCodeUrl: "",
    };
  },
  watch: {},
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      if (row) this.rows = row;
      this.dialogVisible = true;
      await this.getDepartData();
      if (row && row.hasOwnProperty("id")) {
        this.title = "编辑";
        this.ruleForm = Object.assign({}, row);
        this.getImg(this.rows).then((res) => {
          // console.log(res)
          this.fileList = res;
        });
        console.log(this.fileList);
      } else {
        this.title = "新增";
      }
    },
    /* 获取图片 */
    async getImg(row) {
      const res = await this.$axios.get(`/equip/info/getFile?id=${row.id}`);
      if (res.data.code === 200) {
        return res.data.data;
        // this.fileList = res.data.data
      }
    },
    /**
     * @description: 获取所有部门
     * @return {*}
     */
    async getDepartData() {
      const res = await this.$axios.get("/dept/list");
      this.departData = [{ id: "0", deptName: "无" }, ...res.data.data];
    },
    getValue(val) {
      // console.log(val)
      this.ruleForm.deptId = val.id;
      this.ruleForm.eptName = val.deptName;
    },
    /** 上传文件 */
    uploadImage(file) {
      const loading = this.$loading({
        lock: true,
        text: "文件上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const form = new FormData();
      form.append("file", file.file);
      this.$axios.post("/file/files-anon", form).then((res) => {
        if (res && res.data.code === 200) {
          const obj = {
            equipId: this.ruleForm.id,
            fileId: res.data.data.id,
          };
          delete res.data.data.id;
          this.fileList.push(Object.assign(obj, res.data.data));
          if (this.ruleForm.id) {
            this.saveImg(Object.assign(obj, res.data.data));
          }
          setTimeout(() => {
            loading.close();
          }, 200);
        } else {
          this.$message.error(res.data.msg);
          loading.close();
        }
      });
    },
    /* 编辑直接保存图片 */
    async saveImg(obj) {
      const res = await this.$axios.post("/equip/info/saveFile", obj);
      if (res?.data.code === 200) {
        this.$notify.success("提交成功！");
      } else {
        this.$notify.error(res.data.msg);
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibles = true;
    },
    /**  移除上传的文件 */
    async handleRemove(file) {
      if (this.title === "编辑") {
        const res = await this.$axios.post("/equip/info/deleteFile", file);
        if (res.data.code === 200) {
          this.$message.success("删除成功！");
          this.getImg(this.rows).then((res) => {
            this.fileList = res;
          });
        }
      } else {
        let newList = this.fileList.filter(
          (item) => item.fileId !== file.fileId
        );
        this.fileList = newList;
      }
    },
    /** 查看文件图片 */
    checkImage() {
      this.$refs["ResourcePreview"].showDialogs(this.fileList);
    },
    /* 图片或视频上传之前的校验 格式  大小 */
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "video/mp4";
      let isLt5M = true;
      let isLt200M = true;
      if (file.type === "image/jpeg" || file.type === "image/png") {
        isLt5M = file.size / 1024 / 1024 < 5;
      }
      if (file.type === "video/mp4") {
        isLt200M = file.size / 1024 / 1024 < 200;
      }
      if (!isJPG) {
        this.$message.error("上传文件只能是 JPG 、PNG、MP4格式!"); //
      }
      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB!"); //
      }
      if (!isLt200M) {
        this.$message.error("上传视频大小不能超过 200MB!");
      }
      return isJPG && isLt5M && isLt200M;
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.ruleForm.fileList = this.fileList;
          const res = await this.$axios.post("/equip/info/save", this.ruleForm);
          if (res?.data.code === 200) {
            this.$notify.success("提交成功！");
            this.dialogVisible = false;
            this.$emit("getTableInfo");
          } else {
            this.$notify.error(res.data.msg);
          }
        }
      });
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm = {
        equipName: "",
        equipCode: "",
        model: "",
        remark: "",
        location: "",
        deptId: "",
        purchaseDate: "",
        type: "",
        usageCondition: "",
        userId: "",
        fileList: [],
      };
      this.fileList = [];
    },
    // ... existing methods ...
    showQRCode() {
      if (!this.ruleForm.equipCode) {
        this.$message.error("请先输入设备编号");
        return;
      }
      this.qrCodeUrl = this.generateQRCode(this.ruleForm.equipCode); // 生成二维码的URL
      this.qrCodeDialogVisible = true;
    },
    generateQRCode(data) {
      // 这里可以使用一个二维码生成库来生成二维码的URL
      return `https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(
        data
      )}&size=150x150`;
    },
    downloadPDF() {
      // 这里实现下载PDF的逻辑
      const link = document.createElement("a");
      link.href = "/path/to/your/pdf"; // 替换为实际的PDF文件路径
      link.download = "设备编号.pdf";
      link.click();
    },
  },
};
</script>
<style lang="scss" scoped></style>
